//
//  NDContactsPicker.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/14.
//

import SwiftUI
import ContactsUI

struct NDContactsPicker: UIViewControllerRepresentable {
    @Binding var phoneNumber: String?
    @Binding var fullName: String?
    
    func makeUIViewController(context: Context) -> CNContactPickerViewController {
        let picker = CNContactPickerViewController()
        picker.delegate = context.coordinator
        
        // iOS 14 最稳定的配置
        picker.modalPresentationStyle = .formSheet
        picker.modalTransitionStyle = .crossDissolve
        picker.preferredContentSize = CGSize(
            width: min(UIScreen.main.bounds.width - 40, 500),
            height: min(UIScreen.main.bounds.height - 100, 600)
        )
        
        return picker
    }
    
    func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: Context) {
        // 空实现
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, CNContactPickerDelegate {
        let parent: NDContactsPicker
        
        init(_ parent: NDContactsPicker) {
            self.parent = parent
        }
        
        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
            let fullName = "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespaces)
            var phoneNumber = ""
            
            if let firstPhone = contact.phoneNumbers.first {
                phoneNumber = firstPhone.value.stringValue
            }
            
            if fullName.isEmpty {
                NDProgressHUD.showInfo(localizedString("name_isempty"))
                return
            }
            
            if phoneNumber.isEmpty {
                NDProgressHUD.showInfo(localizedString("phone_number_isempty"))
                
                return
            }
        
            parent.fullName = fullName
            parent.phoneNumber = phoneNumber
        }
        
        func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
            // 自动关闭
        }
    }
}
